<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', 'menu.list.searchTable']" />
    <a-card class="general-card" :title="$t('menu.list.searchTable')">
      <a-row>
         <a-col :span="12" class="flex flex-col items-center justify-center">
            <div class="text-xl font-semibold">{{ subOrders }}</div>
            <div>充值订单总计(笔)</div>
         </a-col>
         <a-col :span="12" class="flex flex-col items-center justify-center">
          <span class="text-xl font-semibold">￥{{ subAmounts }}</span>
          <span>充值金额总计(元)</span>
         </a-col>
      </a-row>
      <a-row class="mt-4">
        <a-col :flex="1">
          <a-form :model="formModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
            label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="number" label="学号">
                  <a-input v-model="formModel.number" :placeholder="$t('searchTable.form.number.placeholder')" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="businessOrderNo" label="订单号">
                  <a-input
                    v-model="formModel.businessOrderNo"
                    placeholder="请输入"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  field="filterType"
                  label="状态"
                >
                  <a-select
                  allow-clear
                    v-model="formModel.consumptionStatus"
                    :options="arrConsumpName"
                    :placeholder="$t('searchTable.form.selectDefault')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="createdTime" :label="$t('searchTable.form.createdTime')">
                  <a-range-picker @change="onChange" v-model="formModel.createdTime" style="width: 100%" />
                </a-form-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-item
                  field="status"
                  :label="$t('searchTable.form.status')"
                >
                  <a-select
                    v-model="formModel.status"
                    :options="statusOptions"
                    :placeholder="$t('searchTable.form.selectDefault')"
                  />
                </a-form-item>
              </a-col> -->
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <!-- <a-button  type="primary">
             导出
            </a-button> -->
            <!-- <a-upload action="/">
              <template #upload-button>
                <a-button>
                  {{ $t('searchTable.operation.import') }}
                </a-button>
              </template>
            </a-upload> -->
          </a-space>
        </a-col>
        <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
          <a-button @click="exportFile">
            <template #icon>
              <icon-download />
            </template>
            导出excel
          </a-button>
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"><icon-refresh size="18" /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption v-for="item in densityList" :key="item.value" :value="item.value"
                :class="{ active: item.value === size }">
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox v-model="item.checked" @change="
      handleChange($event, item as TableColumnData, index)
      ">
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table row-key="id" :loading="loading" :pagination="pagination" :columns="(cloneColumns as TableColumnData[])"
        :data="renderData" :bordered="false" :size="size" @page-change="onPageChange">
        <!-- <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template> -->
        <!-- <template #contentType="{ record }">
          <a-space>
            <a-avatar
              v-if="record.contentType === 'img'"
              :size="16"
              shape="square"
            >
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/581b17753093199839f2e327e726b157.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            <a-avatar
              v-else-if="record.contentType === 'horizontalVideo'"
              :size="16"
              shape="square"
            >
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/77721e365eb2ab786c889682cbc721c1.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            <a-avatar v-else :size="16" shape="square">
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/ea8b09190046da0ea7e070d83c5d1731.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            {{ $t(`searchTable.form.contentType.${record.contentType}`) }}
          </a-space>
        </template> -->
        <!-- <template #filterType="{ record }">
          {{ $t(`searchTable.form.filterType.${record.filterType}`) }}
        </template> -->
        <template #waterCardNumber="{ record }">
          {{ record.waterCardNumber ? record.waterCardNumber : '-' }}
        </template>
        <template #createTime="{ record }">
          {{ toFormat('YYYY-MM-DD hh:mm:ss', record.createTime) }}
        </template>
        <template #orderStatus="{ record }">
          {{ getNameOrder(record.orderStatus) }}
        </template>
        <template #consumptionStatus="{ record }">
          {{ getNameConsump(record.consumptionStatus) }}
        </template>
        <template #operations="{ record }">
          <a-button v-if="record.consumptionStatus == 'PENDING' && record.orderStatus == 'PAID'" @click="resetCharge(record)" type="text" size="small">
            补费
          </a-button>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:visible="isShowEdit">

<template #title>
    补费
</template>
<div>
    <a-spin class="w-full" :loading="loadingEdit" tip="创建中...">
        <a-form ref="formRef" :model="form" layout="vertical">
            <a-form-item :rules="[{ required: true }]" field="amount" label="金额">
                <a-input-number :min="0" v-model="form.amount" :precision="2" placeholder="请输入" />
            </a-form-item>
            <a-form-item :rules="[{ required: true }]" field="outTradeNo" label="订单号">
                <a-input v-model="form.outTradeNo" placeholder="请输入" />
            </a-form-item>
            <a-form-item :rules="[{ required: true }]" field="telPhone" label="电话">
                <a-input v-model="form.telPhone" placeholder="请输入" />
            </a-form-item>
            <a-form-item>
                <a-button type="primary" @click="handleOk">提交</a-button>
            </a-form-item>
        </a-form>
    </a-spin>
</div>

<template #footer>
    <div></div>
</template>
</a-modal>
  </div>
</template>

<script lang="ts" setup>
import { toFormat } from "@/utils/format"
import { computed, ref, reactive, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import useLoading from '@/hooks/loading';
import { queryList, PolicyRecord, PolicyParams, deleteOne,recharge,getOrderStats } from '@/api/list';
import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import cloneDeep from 'lodash/cloneDeep';
import Sortable from 'sortablejs';
import { Modal, Button,Message } from '@arco-design/web-vue';
import { baseUrl } from "@/api/interceptor";
type SizeProps = 'mini' | 'small' | 'medium' | 'large';
type Column = TableColumnData & { checked?: true };
const formRef = ref()
const subAmounts = ref(0);
const subOrders = ref(0);
const form = reactive({
  amount: 0,
  telPhone: "",
  outTradeNo: "",
})
const generateFormModel = () => {
  return {
    number: '',
    // name: '',
    // filterType: '',
    createdTime: [],
    status: '',
    startDate:'',
    consumptionStatus:"",
    endDate:'',
    businessOrderNo:''
  };
};
const { loading, setLoading } = useLoading(true);
const { t } = useI18n();
const renderData = ref<PolicyRecord[]>([]);
const formModel = ref(generateFormModel());
const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);

const size = ref<SizeProps>('medium');
  const isShowEdit = ref(false);
  const loadingEdit = ref(false);
const arrOrderName = reactive([
  { id: 'CREATED', name: "已创建" },
  { id: 'PAID', name: "已支付" },
  { id: 'CANCELLED', name: "已取消" },
])
const arrConsumpName = reactive([
  { value: 'PENDING', label: "待消费" },
  { value: 'CONSUMED', label: "已消费" },
  { value: 'REFUNDED', label: "已退款" },
])
const getNameOrder = (k: any) => {
  let r = arrOrderName.find(it => it.id === k)
  return r && r.name ? r.name : '';
}
const getNameConsump = (k: any) => {
  let r = arrConsumpName.find(it => it.value === k)
  return r && r.label ? r.label : '';
}
const basePagination = {
  current: 1,
  pageSize: 10,
  showTotal: true
};
const pagination = reactive({
  ...basePagination
});
const densityList = computed(() => [
  {
    name: t('searchTable.size.mini'),
    value: 'mini',
  },
  {
    name: t('searchTable.size.small'),
    value: 'small',
  },
  {
    name: t('searchTable.size.medium'),
    value: 'medium',
  },
  {
    name: t('searchTable.size.large'),
    value: 'large',
  },
]);
const columns = computed<TableColumnData[]>(() => [
  {
    title: '订单ID',
    dataIndex: 'orderId',
  },
  {
    title: '业务订单号',
    dataIndex: 'businessOrderNo',
  },
  {
    title: '金额',
    dataIndex: 'orderAmount',
  },
  {
    title: '学号',
    dataIndex: 'studentId',
  },
  {
    title: '热水卡号',
    dataIndex: 'waterCardNumber',
    slotName: 'waterCardNumber',
  },
  {
    title: '电话号',
    dataIndex: 'phoneNumber',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    slotName: 'createTime'
  },
  {
    title: '支付状态',
    dataIndex: 'orderStatus',
    slotName: 'orderStatus',
  },
  {
    title: '充值状态',
    dataIndex: 'consumptionStatus',
    slotName: 'consumptionStatus',
  },
  {
    title: t('searchTable.columns.operations'),
    dataIndex: 'operations',
    slotName: 'operations',
  },
]);
const handleOk = async () => {

let rs = await formRef.value.validate();
if (rs) return
let params = Object.assign({}, form)
setLoading(true);
recharge(params).then(
    rs => {
        if (rs.code == 200) {
            Message.success({
                content: '创建成功!',
                duration: 3 * 1000,
            });
            isShowEdit.value = false;
            search();
        }
    }
).finally(
    () => {
      setLoading(false);
    }
)

}
const getStats = () =>{
  getOrderStats({}).then(
    res=>{
      if(res.code == 200){
        if(res.data.orderCount) subOrders.value = res.data.orderCount ;
        if(res.data.totalAmount) subAmounts.value = res.data.totalAmount.toFixed(2);
      }
    }
  )
}
getStats();
const exportFile =async () =>{
  fetch(baseUrl + '/orders/export/all')  
  .then(response => {  
    if (!response.ok) {  
        throw new Error('Network response was not ok');  
    }  
    // 对于Blob或File的下载，我们通常使用response.blob()  
    return response.blob();  
  }).then(
    blob =>{
 // 处理blob数据，如下载  
 const url = window.URL.createObjectURL(blob);  
    const a = document.createElement('a');  
    a.style.display = 'none';  
    a.href = url;  
    // 假设你知道文件名，或者可以从响应头中获取  
    a.download = 'downloaded_file.xlsx'; // 或者从Content-Disposition响应头获取文件名  
    document.body.appendChild(a);  
    a.click();  
    window.URL.revokeObjectURL(url);
    }
  ) 
   
}
const resetCharge = async (r) =>{
let params = {
  amount: r.orderAmount,
  telPhone: r.phoneNumber,
  outTradeNo: r.businessOrderNo,
}
loadingEdit.value = true
recharge(params).then(
    rs => {
        if (rs.code == 200) {
            Message.success({
                content: '更新成功!',
                duration: 3 * 1000,
            });
            isShowEdit.value = false;
            search();
        }
    }
).finally(
    () => {
        loadingEdit.value = false;
    }
)
}
const deleteOneOrder = (id) => {
  Modal.info({
    title: '提示',
    content: '是否删除当前数据？',
    onOk: async () => {
      setLoading(true);
      deleteOne(id).then(
        rs => {
          search();
        }
      ).finally(
        () => {
          setLoading(false);
        }
      );

    }
  });
}
const onChange = (dateString, date) => {
  formModel.value.startDate = dateString[0];
  formModel.value.endDate = dateString[1];
}
const fetchData = async (
  params: any = { ...pagination }
) => {
  setLoading(true);
  try {
    let p:any =Object.assign({},{
     pageSize : pagination.pageSize,
     pageNum : pagination.current,
    },{...params}) 
  
    for (let k in p) {
      if (!p[k]) delete p[k];
    }
    if(p.createdTime) delete p['createdTime'];
    const { data } = await queryList(p);
    renderData.value = data.content;
    pagination.current = params.current;
    pagination.total = data.totalElements;
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};

const search = () => {
  // let p = Object.assign({}, { ...formModel.value })
  fetchData(formModel.value);
};
const onPageChange = (current: number) => {
  pagination.current = current;
  fetchData(formModel.value);
};

fetchData();
const reset = () => {
  formModel.value = generateFormModel();
};

const handleSelectDensity = (
  val: string | number | Record<string, any> | undefined,
  e: Event
) => {
  size.value = val as SizeProps;
};

const handleChange = (
  checked: boolean | (string | boolean | number)[],
  column: Column,
  index: number
) => {
  if (!checked) {
    cloneColumns.value = showColumns.value.filter(
      (item) => item.dataIndex !== column.dataIndex
    );
  } else {
    cloneColumns.value.splice(index, 0, column);
  }
};

const exchangeArray = <T extends Array<any>>(
  array: T,
  beforeIdx: number,
  newIdx: number,
  isDeep = false
): T => {
  const newArray = isDeep ? cloneDeep(array) : array;
  if (beforeIdx > -1 && newIdx > -1) {
    // 先替换后面的，然后拿到替换的结果替换前面的
    newArray.splice(
      beforeIdx,
      1,
      newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
    );
  }
  return newArray;
};

const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById('tableSetting') as HTMLElement;
      const sortable = new Sortable(el, {
        onEnd(e: any) {
          const { oldIndex, newIndex } = e;
          exchangeArray(cloneColumns.value, oldIndex, newIndex);
          exchangeArray(showColumns.value, oldIndex, newIndex);
        },
      });
    });
  }
};

watch(
  () => columns.value,
  (val) => {
    cloneColumns.value = cloneDeep(val);
    cloneColumns.value.forEach((item, index) => {
      item.checked = true;
    });
    showColumns.value = cloneDeep(cloneColumns.value);
  },
  { deep: true, immediate: true }
);
</script>

<script lang="ts">
export default {
  name: 'SearchTable',
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.action-icon {
  margin-left: 12px;
  cursor: pointer;
}

.active {
  color: #0960bd;
  background-color: #e3f4fc;
}

.setting {
  display: flex;
  align-items: center;
  width: 200px;

  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
